import { ResultFile } from '@alilc/lowcode-types';

import { BuilderComponentPlugin, ICompiledModule, IContextData } from '../types';
import { ChunkBuilder } from './ChunkBuilder';
import { CodeBuilder } from './CodeBuilder';
import { prettier } from '../postprocessor';

export function createModuleBuilder(
  options: {
    plugins: BuilderComponentPlugin[];
    contextData?: IContextData;
  }) {
  const chunkGenerator = new ChunkBuilder(options.plugins);
  const linker = new CodeBuilder();

  return async (input: unknown): Promise<ICompiledModule> => {
    let files: ResultFile[] = [];
    const { chunks } = await chunkGenerator.run(input, {
      ir: input,
      chunks: [],
      depNames: [],
      contextData: options.contextData || {},
    });
    chunks.forEach((fileChunkList) => {
      // 生成代码 使用 module plugins 逐行生成
      const content = linker.link(fileChunkList);
      const ext = fileChunkList[0].fileType;
      files.push({
        name: '#', // 框架需要而已
        ext, // jsx, css
        content: prettier(content, ext)
      });
    });
    return { files };
  }
}
